from imutils import paths
import cv2 as cv
from skimage import io
from os.path import basename,dirname
import numpy as np
import pickle

face_cascade = cv.CascadeClassifier("haarcascade_frontalface_alt.xml")

name_dict={"chenyixun":0,"linjunjie":1,"zhangguorong":2,"zhangxueyou":3,"zhoujielun":4}

n = 0
X = []
y = []
# 该代码可以实现循环img文件夹中以及所有子文件夹内的图像，不用再额外签到循环语句
for i in paths.list_images("img"):
    # dirname -> 获取图像文件的完整路径名,比如: img/ldh/ia_100001239.jpg
    # basename -> 获取图像文件所在的文件夹的名称, 比如上例中的:ldh
    #             因为所有图像都在其类别对应文件夹中，即可直接获得图像类别
    # name_dict[basename] -> 类别对应数字，比如上例中的:name_dict[ldh] -> 1
    label=name_dict[basename(dirname((i)))]
    print(f"处理标签为{label}的图片:{i}")

    img = cv.imread(i,0)                        # 1. 读取图像
    img = cv.equalizeHist(img)                  # 2. 加强对比度
    faces = face_cascade.detectMultiScale(img)  # 3. 识别出图像中的所有正脸

    for (x_ul, y_ul, w, h) in faces:
        face = img[y_ul:y_ul+h,x_ul:x_ul+w]     # 截取面部区域
        face_resized = cv.resize(face, (32,32)) # 把面部区域调整大小
        X.append(face_resized.ravel())          # 把图像拉直放入X
        y.append(label)                         # 把对应的标签放入y

print(f"np.shape(X)={np.shape(X)}")
print(f"np.shape(y)={np.shape(y)}")

with open("X", 'wb') as f:
   pickle.dump(X, f)

with open("y", 'wb') as f:
   pickle.dump(y, f)